<template>
  <!-- 临建设施策划表 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules" :class="editModel == 0 ? '' : 'rulesForm'">
    <!-- 表格 -->
    <a-card :bordered="false">
      <title-name title="临建设施策划表"></title-name>
      <custom-form :formList="formTextarea" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"></custom-form>
      <div>
        <a-button type="primary" @click="addLine" :disabled="editModel == 0">增行</a-button>
        <a-button @click="delLine" style="margin-left: 20px" :disabled="editModel == 0">删除行</a-button>
      </div>
      <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
        <template v-slot:table>
          <a-form-model-item class="formTable" label=" " :colon="false">
            <a-table :row-selection="rowSelection" ref="formTable" bordered :columns="columns" :data-source="form.list" :pagination="false">
              <template v-for="col in ['type', 'mainMeasure', 'principalId','sort']" :slot="col" slot-scope="text, record, index">
                <div :key="col" class="form-item">
                  <template>
                    <BaseInput  :maxLength='300'  v-if="col === 'mainMeasure'" v-model="record[col]" :disabled="editModel == 0"></BaseInput>
                    <div v-else-if="col === 'type'">
                      <BaseInput  :maxLength='300'  v-if="index > 9" v-model="record[col]" :disabled="editModel == 0"></BaseInput>
                      <span v-else>{{ record[col] }}</span>
                    </div>
                    <ASelectOrgPeople
                      v-else-if="col === 'principalId'"
                      :disabled="editModel == 0"
                      placeholder="请选择"
                      :init="false"
                      :orgId="projectDeptOrgId"
                      key-value="projectOrgId"
                      @onSelectChange="(e) => record['principalName'] = e.name"
                      option-key="id"
                      v-model="record[col]"
                    ></ASelectOrgPeople>
                     <span v-else>{{record[col]}}</span>
                  </template></div
              ></template>
            </a-table>
          </a-form-model-item>
        </template>
      </custom-form>
    </a-card>
  </a-form-model>
   
</template>

<script>
import { querySchemeTemporaryFacilitiesDetail,batchUpdateSchemeTemporaryFacilities} from '@/api/project/plannManagement/qverlayFacilitie.js' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import { isNull } from './model.js'
const columns = [
   {title: '序号',width: 80,dataIndex: 'sort',align: 'center'},
  { title: '类型', dataIndex: 'type', align: 'center', scopedSlots: { customRender: 'type' }, width: 300 },
  { title: '主要措施及分项预算、来源及建设周期、处置方案等', dataIndex: 'mainMeasure', align: 'center', scopedSlots: { customRender: 'mainMeasure' } },
  { title: '负责人', dataIndex: 'principalId', align: 'center', scopedSlots: { customRender: 'principalId' }, width: 300 }
]
export default {
  name: 'mainProcess' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    ASelectOrgPeople
  },
  props: {
    statusBasicSuc: {
      type: Boolean,
      default: () => {}
    }
  },
  data() {
    return {
      columns,
      loading: false, // 加载控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      selectedRowKeys: [],
      projectDeptOrgId: this.$currentPost().orgId,
      tableData:[
          { type: '临建房-办公区', mainMeasure: '', principalId: null, sort: '1',key:'1'},
          { type: '临建房-管理人员生活区', mainMeasure: '', principalId: null, sort: '2',key:'2'},
          { type: '临建房-工人生活区', mainMeasure: '', principalId: null, sort: '3',key:'3'},
          { type: '项目大门', mainMeasure: '', principalId: null, sort: '4',key:'4'},
          { type: '围墙围挡', mainMeasure: '', principalId: null, sort: '5',key:'5'},
          { type: '场地硬化', mainMeasure: '', principalId: null, sort: '6',key:'6'},
          { type: '临时道路', mainMeasure: '', principalId: null, sort: '7',key:'7'},
          { type: '办公桌、椅', mainMeasure: '', principalId: null, sort: '8',key:'8'},
          { type: '临水临电设施', mainMeasure: '', principalId: null, sort: '9',key:'9'},
          { type: '其他', mainMeasure: '', principalId: null, sort: '10',key:'10'}
        ],
      form: {
        gradeBudget:null,
        list: []
      }, // 表单
      id: '',
      rules: { gradeBudget: [{ required: true, message: '请输入项目临建设施配置等级、预算总金额' }] }, // 校验规则
      init: false // 初始化控件
    }
  },
 watch: {
  statusBasicSuc: {
      handler(val, oldVal) {
        let form = this.$clone(this.form)
        form.status = this.status
        form.schemeDetailId = this.id
        form.changed = this.pageType == 'change' ? true : false // 是编辑还是变更
        val && this.statusBasicSucFn(form);
      },
      deep: true
    }
  },
  created() {},
  async mounted() {
    await this.getDetailData()
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isDeleteButton * 1 < 1
          }
        })
      }
    },
    formList() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    },
    formTextarea() {
      return [
        {
          keyName: 'gradeBudget',
          type: 'BaseTextarea',
          label: '项目临建设施配置等级、预算总金额',
          placeholder: '(要求满足区域分级配置要求)',
          disabled: this.editModel == 0,
          span: 24,
           attrs: {
            maxLength: 3000
          }
        }
      ]
    }
  },
  methods: {
    getPeople(e,index){
      console.log(e,index)
    },
    //添加行
    addLine() {
      this.form.list.push({
        sort: this.form.list.length+1,
        key:this.form.list.length+1,
        type: null,
        mainMeasure: null,
        principalId: null,
      })
    },
    delLine() {
      let that = this
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择要删除的数据')
        return false
      }
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提示?',
        content: `请确认是否要删除?`,
        onOk() {
          that.sureDel()
        },
        onCancel() {}
      })
    },
    sureDel() {
      if (this.selectedRowKeys.length) {
        this.selectedRowKeys.map((item) => {
          delete this.form.list[item - 1]
        })
      }
      this.selectedRowKeys = []
      let filterBlankArr = this.form.list.filter((item) => item) //过滤数组空白的数据
      this.form.list = filterBlankArr
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
       this.$emit('update:spinning', true)
         let reqObj = {
          schemeDetailId: this.id,
          latestData:true
        }
        if (this.version) {
          reqObj.version = this.version,
          reqObj.latestData = false
        }
        querySchemeTemporaryFacilitiesDetail(reqObj)
          .then((res) => {
           this.$emit('update:spinning', false)
           this.form = { ...this.form, ...res.data }
           this.form.list.length && this.form.list.map((item)=>item.key=item.sort)
              if (!this.form.list || !this.form.list.length) {
                this.form.list = this.tableData
              }
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
    },
    /**
     * 提交表单
     */
    qverlayFacilitieSubmit(baseData) {
      let dataDable = this.$clone(this.form.list);
      let rulesArr = []
      dataDable.map((item) => {
        let a = Object.values(item).every((oItem) =>isNull(oItem))
        a && rulesArr.push(a)
      })
      let flag = rulesArr.length === dataDable.length
      if (!flag) {
        this.$message.warning('请完善表格数据')
        return
      }
      if (!this.validateForm()) {
        return
      }
      this.sure(1,baseData)
    },
    sure(str,baseData) {
      let that = this
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交?`,
        onOk() {
          that.submitFn(str,baseData)
        },
        onCancel() {}
      })
    },
    qverlayFacilitieSaveDrafts(baseData) {
      //保存草稿
      this.submitFn(0,baseData)
    },

    submitFn(status, baseData) {
      this.$emit('update:spinning', true)
      baseData.schemeDetailId = this.id
      baseData.status = status
      this.status = status;
      this.$emit('updateBasicDetail', baseData)
    },
    statusBasicSucFn(formData){
      formData.list.map((item)=>{
        delete item.key
        if(!isNull(item.isDeleteButton)){
          item.isDeleteButton = 1;
        }
      })
        let msg = this.status * 1 === 1 ? '提交' : '保存草稿'
        let api = batchUpdateSchemeTemporaryFacilities
        api(formData).then(() => {
            this.$emit('update:spinning', false)
            this.$message.success(`${msg}成功！`)
            this.status * 1===1 && this.$multiTab.close()
        })
        .catch(() => {
          this.$message.warning(err.data.message)
          this.$emit('update:spinning', false)
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.scene {
  display: block;
  margin: 10px 0 10px 60px;
  color: rgba(0, 0, 0, 0.85);
}
.rulesForm {
  @{deep} .ant-input,
  @{deep} .ant-input-mainMeasure-input,
  @{deep} .ant-select .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  @{deep} .mandatory .ant-input {
    border-color: #d9d9d9;
    background-color: #fff;
  }
  @{deep} .setPlaceholder {
    .ant-select-selection__placeholder {
      display: block !important;
    }
  }
}
@{deep} .formTable {
  .ant-form-item-label {
    width: 0;
  }
  .ant-form-item-control-wrapper {
    width: 100%;
  }
}
</style>
